package org.btik.light.dao;

import org.btik.light.meta.DevMo;
import org.btik.light.meta.LightNode;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * light server原有自带cache,改名区分Light Cache组件
 */
public class LightServerCache {

    static private final Map<String, LightNode> nodes = new ConcurrentHashMap<>();

    static private final Map<String, DevMo> mos = new ConcurrentHashMap<>();

    static private final Map<LightNode, ConcurrentHashMap<String, DevMo>> nodeTree = new ConcurrentHashMap<>();

    static LightNode getNodeByLocation(String location) {
        return nodes.get(location);
    }

    static LightNode addNode(LightNode lightNode) {
        return nodes.put(lightNode.location(), lightNode);
    }

    static DevMo getMO(String sn) {
        return mos.get(sn);
    }

    static Collection<DevMo> getChildren(LightNode lightNode) {
        HashSet<DevMo> devMos = new HashSet<>();
        nodeTree.get(lightNode).forEach((k, v) -> devMos.add(v));
        return devMos;
    }


    public static void addMO(LightNode lightNode, DevMo mo) {
        mos.put(mo.getSn(), mo);

        nodeTree.computeIfAbsent(lightNode, (k) -> new ConcurrentHashMap<>()).put(mo.getSn(), mo);
    }
}
